package com.smzd.framework.utils;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

public class JsonHelper {
	public static String getFailJsonString(){
		return getFailJsonString(null, null, null);
	}
	public static String getFailJsonString(String msg){
		return getFailJsonString(null, null, msg);
	}
	public static String getFailJsonString(String key, Object value){
		return getFailJsonString(key, value, null);
	}
	public static String getFailJsonString(String key, Object value, String msg){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", false);
		if(key!=null){
			map.put(key, value);
		}
		if(msg!=null){
			map.put("err", msg);
		}
		return getJsonString(map);
	}
	public static String getFailJsonString(Map<String, Object> map){
		if(map==null){
			return getFailJsonString();
		}
		map.put("success", false);
		return getJsonString(map);
	}
	
	public static String getSuccessJsonString(){
		return getSuccessJsonString(null, null, null);
	}
	public static String getSuccessJsonString(String msg){
		return getSuccessJsonString(null, null, msg);
	}
	public static String getSuccessJsonString(String key, Object value){
		return getSuccessJsonString(key, value, null);
	}
	public static String getSuccessJsonString(String key, Object value, String msg){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", true);
		if(key!=null){
			map.put(key, value);
		}
		if(msg!=null){
			map.put("msg", msg);
		}
		return getJsonString(map);
	}
	public static String getSuccessJsonString(Map<String, Object> map){
		if(map==null){
			return getSuccessJsonString();
		}
		map.put("success", true);
		return getJsonString(map);
	}
    public static String getSuccessJsonString(Object[] array){
        if(array==null||array.length==0){
            return getSuccessJsonString();
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", true);
        map.put("data", array);
        return getJsonString(map);
    }
	public static String getJsonString(Map<String, Object> map){
		JSONObject obj = new JSONObject();
		if(map!=null){
			for(String key : map.keySet()){
				Object value = map.get(key);
				if(value!=null){
				    System.out.println(key+".value.class="+value.getClass().getName());
				}else{
				    obj.accumulate(key, null);
				    System.out.println(key+".value.class=null");
				    continue;
				}
				if(value instanceof Integer){
					obj.accumulate(key, (Integer)value);
				}else
				if(value instanceof Long){
					obj.accumulate(key, (Long)value);
				}else
				if(value instanceof Float){
					obj.accumulate(key, (Float)value);
				}else
				if(value instanceof Double){
					obj.accumulate(key, (Double)value);
				}else
				if(value instanceof Boolean){
					obj.accumulate(key, (Boolean)value);
				}else{
					obj.accumulate(key, value);
				}
			}
		}
		return obj.toString();
	}

}
